﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

const string QueueName = "Hello";



//基础的RabbitMQ工厂
var factory = new ConnectionFactory()
{
    HostName = "localhost",
    Port = 5672,
    UserName = "guest",
    Password = "guest"
};


 using  var connection = await factory.CreateConnectionAsync();

var channel = await connection.CreateChannelAsync();
await channel.QueueDeclareAsync(
    queue: QueueName,
     durable: false,      // 是否持久化（重启后保留）
     exclusive: false,    // 是否排他（仅当前连接可用）
     autoDelete: false,   // 是否自动删除（无消费者时）
     arguments: null
    );

Console.WriteLine($"✅ 正在监听队列 '{QueueName}'。按任意键退出...");

var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (model, ea) =>
{
    var body = ea.Body.ToArray();
    var message = Encoding.UTF8.GetString(body);
    Console.WriteLine($"📩 收到消息: {message}");
};

await channel.BasicConsumeAsync(
            queue: QueueName,
            autoAck: true,      // 自动确认
            consumer: consumer  // 使用上面创建的消费者
        );

Console.ReadKey();